package com.skivingcloud.feign.conf;

import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestClient;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.util.Collections;

/**
 * @author hushouquan
 */
@Configuration
public class RestTemplateConfig{
    @Resource
    private RestTemplateTokenInterceptor restTemplateTokenInterceptor;
    
    // 配置 RestTemplate
    @Bean
    @LoadBalanced
    public RestTemplate restTemplate(ClientHttpRequestFactory factory){
        RestTemplate restTemplate = new RestTemplate(factory);
        restTemplate.setInterceptors(Collections.singletonList(restTemplateTokenInterceptor));
        return restTemplate;
    }
    
    @Bean
    public ClientHttpRequestFactory simpleClientHttpRequestFactory(){
        // 创建一个 httpClient 简单工厂
        HttpsClientRequestFactory factory = new HttpsClientRequestFactory();
        // 设置连接超时
        factory.setConnectTimeout(60*1000);
        // 设置读取超时
        factory.setReadTimeout(60*1000);
        return factory;
    }
    
    /**
     * 这个是用来调用外部接口的restTemplate
     * @param factory 工厂
     * @return restTemplate
     */
    @Bean
    public RestTemplate restTemplateOuter(ClientHttpRequestFactory factory){
        RestTemplate restTemplate = new RestTemplate(factory);
        restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(StandardCharsets.UTF_8));
        return restTemplate;
    }
    
    @Bean
    public RestClient restClient(@Qualifier("restTemplate") RestTemplate restTemplate){
        return RestClient.builder(restTemplate).build();
    }
}
